import logging
from logging.handlers import TimedRotatingFileHandler

from config.config import path
import os

class GetLog:
    """单例日志器"""

    def __init__(self, log_name="llz", log_level=logging.INFO):
        self.__logger = logging.getLogger(log_name)

        # 避免在类被实例化多次时重复添加处理器
        if not self.__logger.handlers:
            self.__logger.setLevel(log_level)

            # 控制台处理器
            st = logging.StreamHandler()

            # 文件处理器（定时轮换）
            log_directory = f"{path}/../log/"
            if not os.path.exists(log_directory):
                os.makedirs(log_directory)
            log_path = os.path.join(log_directory, f"{log_name}.log")
            th = TimedRotatingFileHandler(
                filename=log_path,
                when='midnight',
                interval=1,
                backupCount=7,
                encoding="utf-8"
            )

            # 格式化器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fm = logging.Formatter(fmt=fmt)

            # 将格式化器添加到处理器中
            th.setFormatter(fm)
            st.setFormatter(fm)

            # 将处理器添加到日志器中
            self.__logger.addHandler(st)  # 控制台输出
            self.__logger.addHandler(th)

    def get_logger(self):
        return self.__logger


logger_instance = GetLog(log_name="monkey_log", log_level=logging.DEBUG)
logger = logger_instance.get_logger()




if __name__ == '__main__':
    # 初始化日志器
    logger_instance = GetLog(log_name="monkey_log", log_level=logging.DEBUG)
    logger = logger_instance.get_logger()

    # 使用日志器
    logger.info("信息日志")
    logger.debug("调试信息")
